package com.shenzhen.horselive.ui.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;

import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.base.AppBarActivity;
import com.shenzhen.horselive.beans.ApplyHistory;
import com.shenzhen.horselive.beans.CommResponseBean;
import com.shenzhen.horselive.beans.OpenCardDetailsBean;
import com.shenzhen.horselive.beans.UserAcountBean;
import com.shenzhen.horselive.databinding.ActivityOpenCardDieatilsBinding;
import com.shenzhen.horselive.databinding.ActivityOpenCardHistoryBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.LoadingViewObserver;
import com.shenzhen.horselive.ui.dialog.DialogCaneclApply;
import com.shenzhen.horselive.utils.DialogManager;
import com.shenzhen.horselive.utils.TimeUtils;

public class OpenCardDieatilsActivity extends AppBarActivity {

    ActivityOpenCardDieatilsBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding =  ActivityOpenCardDieatilsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setStyleDark();
        setTitle("预约详情");
        initData();
    }

    private void initData() {
        String  id  = getIntent().getStringExtra("id");
        if (id==null)
            return;

        ApiFactory.getApiService().openCardDetails(User.get().getMyInfo().getToken(),id)
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<OpenCardDetailsBean>(this) {
                    @Override
                    protected void onNextInActive(OpenCardDetailsBean openCardDetailsBean) {
                        if (openCardDetailsBean.isSuccess())
                        {
                            //处理数据
                            playData(openCardDetailsBean.getData());

                        }else
                        {
                            showToast(openCardDetailsBean.getErrMessage());
                        }
                    }
                });

    }

    private void playData(OpenCardDetailsBean.DataBean data) {



        OpenCardDetailsBean.DataBean  dataBean  =data;
        if (dataBean==null)
        {
            return;
        }
        // * 1=>’预约中’,2=>’已失效’,0=>’待提交’,3=>’待邮寄’,4=>’已邮寄’ ,5=>’’权限未开通‘,6=>’’已取消’
        binding.containerCanCancel.setVisibility(View.GONE);
        //预约的详情页面
        binding.containerCancelDetails.setVisibility(View.GONE);
        switch (dataBean.getOrderStatus()) {
            case 0:
                //待提交
                binding.imgType.setImageResource(R.mipmap.ico_open_card_wait_tijiao);
                binding.tvNotice0.setText("您的卡片正在待提交中，请耐心等待");
                binding.tvNotice1.setVisibility(View.VISIBLE);
                binding.tvNotice1.setText("申请时间：" + dataBean.getCreateTime());
                binding.tvNotice2.setVisibility(View.GONE);
                binding.linerKuaidi.setVisibility(View.GONE);
                break;
            case 1:
                //卡屏预约中
                binding.imgType.setImageResource(R.mipmap.ico_yuyue_zhong);
                binding.tvNotice0.setText("您的卡片正在预约中，请耐心等待");
                binding.tvNotice1.setText("申请时间：" + dataBean.getCreateTime());
                binding.tvNotice2.setVisibility(View.GONE);
                //快递
                binding.linerKuaidi.setVisibility(View.GONE);
                break;
            case 2:
                //已经失效
                binding.imgType.setImageResource(R.mipmap.ico_open_card_shixiao);
                binding.tvNotice0.setText("您的卡片已经预约失效");
                binding.tvNotice1.setVisibility(View.GONE);
                binding.tvNotice2.setVisibility(View.GONE);
                binding.linerKuaidi.setVisibility(View.GONE);
                break;
            case 3:
                //待邮寄
                binding.imgType.setImageResource(R.mipmap.ico_dai_youji);
                binding.tvNotice0.setText("您的卡片已经预约成功，等待邮寄中");
                binding.tvNotice1.setText("联通客服会尽快与您联系，请保持电话通畅");
                binding.tvNotice2.setText("申请时间：" + dataBean.getCreateTime());
                //快递
                binding.linerKuaidi.setVisibility(View.GONE);
                break;
            case 4:
                //已经邮寄
                binding.imgType.setImageResource(R.mipmap.ico_yiyouji);
                binding.tvNotice0.setText("您的卡片已邮寄，请注意查收");
                binding.tvNotice1.setText("邮寄时间：" + dataBean.getUpdateTime());
                binding.tvNotice2.setVisibility(View.GONE);
                binding.linerKuaidi.setVisibility(View.VISIBLE);
                //快递单号
                binding.tvKuaidiName.setText("快递名称：" + dataBean.getWaybillCompany());
                binding.tvKusidiNumber.setText("快递单号：" + dataBean.getWaybillNumber());
                binding.tvClip.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //获取剪贴板管理器：
                        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        // 创建普通字符型ClipData
                        ClipData mClipData = ClipData.newPlainText("Label", dataBean.getWaybillNumber());
                        // 将ClipData内容放到系统剪贴板里。
                        cm.setPrimaryClip(mClipData);
                        showToast("快递单号已复制");
                    }
                });
                break;
            case 5:
                //5=>’’权限未开通
                binding.imgType.setImageResource(R.mipmap.ico_daikaitong_details);
                binding.tvNotice0.setText("您申请的预约城市开卡权限等待开通中");
                binding.tvNotice1.setText("申请时间：" + dataBean.getCreateTime());
                binding.tvNotice2.setVisibility(View.GONE);
                //快递信息
                binding.linerKuaidi.setVisibility(View.GONE);

                //待开通的信息
                binding.containerCanCancel.setVisibility(View.VISIBLE);

                binding.tvAmount.setText("¥" + dataBean.getPayAmount());
                if (dataBean.getChannelId().equals("SPSDKWX_PAY")) {
                    binding.tvPayWay.setText("微信");
                } else {
                    binding.tvPayWay.setText("支付宝");
                }
                binding.tvOrderCode.setText(dataBean.getOrderCode());
                binding.tvPayTime.setText(dataBean.getPayTime());
                //提示信息
                binding.tvWeixinTishi.setText(String.format("申请成功后，%s天以内您可随时取消预约，超过%s天以后，您将无法取消预约。", dataBean.getCanCancelDays(), dataBean.getCanCancelDays()));

                //倒计时时间
                String endTime = dataBean.getOrderEndTimestamp();
                if (endTime != null)
                {
                    if (Long.parseLong(endTime)*1000<=System.currentTimeMillis())
                    {
                        //隐藏按钮，不需要倒计时
                        binding.btGo.setVisibility(View.GONE);
                        binding.tvTextCanceltime.setVisibility(View.GONE);
                        binding.tvCountTime.setVisibility(View.GONE);
                    }else
                    {
                        binding.tvTextCanceltime.setVisibility(View.VISIBLE);
                        binding.tvCountTime.setVisibility(View.VISIBLE);
                        binding.btGo.setVisibility(View.VISIBLE);
                    countDownTime(dataBean.getOrderEndTimestamp());
                        //取消按钮
                        binding.btGo.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                openDialog(dataBean.getPayAmount(),dataBean.getOrderCode());
                            }
                        });
                    }
                }
                else
                {

                }

                break;

            case 6:
                //已经取消
                binding.imgType.setImageResource(R.mipmap.ico_opencard_yiquxiao);
                binding.tvNotice0.setText("您的预约开卡申请已取消");
                binding.tvNotice1.setText("取消时间："+dataBean.getUpdateTime());
                binding.tvNotice2.setVisibility(View.GONE);
                //快递信息
                binding.linerKuaidi.setVisibility(View.GONE);
                //详情的信息页面
                binding.containerCancelDetails.setVisibility(View.VISIBLE);

                binding.tvAmount0.setText("¥"+dataBean.getPayAmount());
                if (dataBean.getChannelId().equals("SPSDKWX_PAY"))
                {
                    binding.tvPayWay0.setText("微信");
                }
                else {
                    binding.tvPayWay0.setText("支付宝");
                }
                binding.tvOrderCode0.setText(dataBean.getOrderCode());
                binding.tvPayTime0.setText(dataBean.getPayTime());

                //折算峰值
                getFenzhiRatio(dataBean.getPayAmount());
                break;

            default:
                binding.imgType.setImageResource(R.mipmap.ico_yuyue_zhong);
                binding.tvNotice0.setText("您的卡片正在预约中，请耐心等待");
                binding.tvNotice1.setText("邮寄时间："+dataBean.getCreateTime());
                binding.tvNotice2.setVisibility(View.GONE);
                binding.linerKuaidi.setVisibility(View.GONE);
                break;
        }
        binding.tvName.setText(dataBean.getOpenName());
        binding.tvCity.setText(dataBean.getOpenCity()+data.getOpenArea());
        binding.tvPhone.setText(dataBean.getOpenPhone());
        binding.tvTaocanName.setText(dataBean.getSchemeName());
        binding.tvAddrName.setText(dataBean.getWaybillArea());
        binding.tvAddrDetails.setText(dataBean.getWaybillAddress());

    }

    private void getFenzhiRatio(String payAmount) {
        ApiFactory.getApiService().accountTypes(User.get().getMyInfo().getToken()
                ,"1").compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<UserAcountBean>(this) {
                    @Override
                    protected void onNextInActive(UserAcountBean userAcountBean) {
                        if (userAcountBean.isSuccess())
                        {
                            double  fenzhi = Double.parseDouble(payAmount)*Double.parseDouble(userAcountBean.getData().getOneRatio());
                            binding.tvFenzhi.setText(formatFuckingNumber(fenzhi+""));
                        }
                        else
                        {
                            showToast(userAcountBean.getErrMessage());
                        }
                    }
                });
    }

    private void openDialog(String payAmount, String orderCode) {
        ApiFactory.getApiService().accountTypes(User.get().getMyInfo().getToken()
        ,"1")
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<UserAcountBean>(this) {
                    @Override
                    protected void onNextInActive(UserAcountBean userAcountBean) {
                        if (userAcountBean.isSuccess())
                        {
                            DialogManager.getInstance().showCancelApply(getContext(), payAmount, userAcountBean.getData()
                                    , new DialogCaneclApply.OnButtonClick() {
                                        @Override
                                        public void onClick() {
                                            //取消预约
                                            ApiFactory.getApiService().cancelApply(User.get().getMyInfo().getToken()
                                            ,orderCode)
                                                    .compose(SchedulersCompat.applyIoSchedulers())
                                                    .safeSubscribe(new LoadingViewObserver<CommResponseBean>(OpenCardDieatilsActivity.this) {
                                                        @Override
                                                        protected void onNextInActive(CommResponseBean commResponseBean) {
                                                            if (commResponseBean.isSuccess())
                                                            {
                                                                showToast("取消成功");
                                                                finish();
                                                            }else
                                                            {
                                                                showToast(commResponseBean.getErrMessage());
                                                            }
                                                        }
                                                    });

                                        }
                                    });
                        }else
                        {
                            showToast(userAcountBean.getErrMessage());
                        }
                    }
                });



    }

    CountDownTimer  countDownTimer;
    private void countDownTime(String orderEndTimestamp) {
        if (orderEndTimestamp==null)
        {
            return;
        }
        if (countDownTimer!=null)
        {
            countDownTimer.cancel();
            countDownTimer=null;
        }
        if (countDownTimer==null)
        {
            countDownTimer =  new CountDownTimer(Long.parseLong(orderEndTimestamp)*1000-System.currentTimeMillis(),1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    binding.tvCountTime.setText(TimeUtils.generateTime(millisUntilFinished));
                }
                @Override
                public void onFinish() {
                }
            };
            countDownTimer.start();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer!=null)
        {
            countDownTimer.cancel();
            countDownTimer=null;
        }
    }

    public static void start(Context context, String  id) {
        Intent starter = new Intent(context, OpenCardDieatilsActivity.class);
        starter.putExtra("id",id);
        context.startActivity(starter);
    }

}